#include <iostream>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string>
#include <cstring>
#include <unistd.h>
#include <cstdlib>
#include <cstdio>

void Usage(std::string proc)
{
    std::cout << "\n\r" << proc << "serverip serverport" << std::endl;
}
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }
    std::string serverip = argv[1];
    uint16_t serverport = atoi(argv[2]);

    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd == -1)
    {
        perror("sock fail");
        exit(1);
    }

    // struct sockaddr_in server;
    // memset(&server, 0, sizeof(server));
    // server.sin_family = AF_INET;
    // //inet_aton(serverip.c_str(), &(server.sin_addr));
    // inet_pton(AF_INET, serverip.c_str(), &(server.sin_addr));
    // htons(server.sin_port);

    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    inet_pton(AF_INET, serverip.c_str(), &(server.sin_addr));

    int len = sizeof(server);
    if(connect(sockfd, (struct sockaddr*)&server, len) == -1)
    {
        perror("connect fail");
        exit(0);
    }
    std::cout << "connect success" << std::endl;
    char buffer[1024];
    while(true)
    {
        std::cout << "Please Enter#";
        std::string message;
        std::getline(std::cin, message);
        ssize_t n =write(sockfd, message.c_str(), message.size());
        if(n < 0)
        {
            std::cerr << "write error" << std::endl;
        }
        n = read(sockfd, buffer, sizeof(buffer)-1);
        if(n > 0)
        {
            buffer[n] = 0;
            std::cout << buffer << std::endl;
        }
        else 
        {
            break;
        }
        close(sockfd);

    }
    return 0;
}